package cn.wangzg.getdatademo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    String path="https://www.wanandroid.com/article/list/0/json";
    private List<Article> articleList=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(){
            @Override
            public void run() {
                String jsonString = getJsonString(path);
                System.out.println(jsonString);
                articleList=parseJson(jsonString);
                for (int i = 0; i < articleList.size(); i++) {
                    System.out.println(articleList.get(i).getTitle());
                }
            }
        }.start();
    }
    private List<Article> parseJson(String strJson){
        List<Article> articles=new ArrayList<>();
        try {
            JSONObject object=new JSONObject(strJson);
            int errorCode = object.optInt("errorCode");
            if(errorCode!=0) return null;
            JSONObject object1 = object.optJSONObject("data");
            JSONArray datas = object1.optJSONArray("datas");
            for(int i=0;i<datas.length();i++){
                JSONObject object2 = datas.optJSONObject(i);
                String title = object2.optString("title");
                String author = object2.optString("author");
                String link = object2.optString("link");
                Article article=new Article(title,author,link);
                articles.add(article);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return articles;
    }
    private String getJsonString(String path){
        try {
            URL url=new URL(path);
            HttpURLConnection cn= (HttpURLConnection) url.openConnection();
            InputStream inputStream = cn.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer=new StringBuffer();
            String line=null;
            while ((line=br.readLine())!=null){
                buffer.append(line);
            }
            return buffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}